
//
//  FDAWSDownUpLoadTool.m
//  FD
//
//  Created by xiaofang wang on 2018/12/6.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//

#import "FDAWSDownUpLoadTool.h"
#import <AWSS3/AWSS3.h>

@implementation FDAWSDownUpLoadTool

/**
 1.使用亚马逊下载HTML模板和富文本html
 
 @param key 模板key、richtext key
 @param complection 成功回调解析好的html字符串
 
 eg0：https://s3-eu-west-1.amazonaws.com/fudiandmore/public/1f9c826f0139458c9e48363f99fa8e1f
 eg1:
 */
+ (void)fdAWSDownloadWithKey:(NSString *)key complectionBlock:(void (^)(NSString * _Nonnull))complection failBlock:(void (^)(void))failure {
    
    if ([NSString isEmptyString:key]) { //如果为空,直接返回
        FDLog(@"key 为空,操作无效");
        
        failure(); //1-5失败回调
        return;
    }
    
    NSString *awsDomain = [NSString stringWithFormat:@"https://s3-eu-west-1.amazonaws.com/fudiandmore/"];
    
    FDLog(@"模板或者资源地址:%@%@",awsDomain,key);
    
    
    //Create the completion handler for the transfer
    AWSS3TransferUtilityDownloadCompletionHandlerBlock completionHandler = ^(AWSS3TransferUtilityDownloadTask *task, NSURL *location, NSData *data, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                FDLog(@"错误:%@",error);

                failure(); //1-5失败回调
            }
            
            if (data) {
                FDLog(@"下载成功");
                //NSData 转字符串
                NSString *htmlStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//                FDLog(@"文字内容是:%@",htmlStr);
                
                //回调下载结果
                if (complection) {
                    complection(htmlStr);
                }
            }
        });
    };
    
    //Create the TransferUtility expression and add the progress block to it.
    //This would be needed to report on progress tracking
    AWSS3TransferUtilityDownloadExpression *expression = [AWSS3TransferUtilityDownloadExpression new];
    expression.progressBlock = ^(AWSS3TransferUtilityTask *task, NSProgress *progress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            //            weakSelf.progressView.progress = progress.fractionCompleted;
        });
    };
    
    
    AWSS3TransferUtility *transferUtility = [AWSS3TransferUtility defaultS3TransferUtility];
    [[transferUtility downloadDataFromBucket:FDAWSS3BucketName
                                         key:key
                                  expression:expression
                           completionHandler:completionHandler] continueWithBlock:^id(AWSTask *task) {
        if (task.error) {
            NSLog(@"Error: %@", task.error);
        }
        if (task.result) {
            dispatch_async(dispatch_get_main_queue(), ^{
                FDLog(@"下载中.....");
            });
        }
        
        return nil;
    }];

}
@end
